/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.remote;

import com.googlecode.actorom.Actor;
import com.googlecode.actorom.FailoverPolicy;
import com.googlecode.actorom.FutureResult;
import com.googlecode.actorom.ThreadingPolicy;
import com.googlecode.actorom.impl.core.AbstractTopology;
import com.googlecode.actorom.impl.remote.RemoteActorProxy;
import com.googlecode.actorom.support.ThreadingPolicies;
import com.googlecode.actorom.impl.remote.channel.MessageChannel;
import com.googlecode.actorom.impl.remote.channel.CommandCallback;
import com.googlecode.actorom.impl.remote.channel.MessageChannelConnector;
import com.googlecode.actorom.impl.remote.channel.protocol.Host;
import com.googlecode.actorom.impl.remote.channel.protocol.CommandHeader;
import com.googlecode.actorom.impl.remote.channel.protocol.CompleteCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.IsActiveCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.LinkCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.SendCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.SendWithFutureCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.UnlinkCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.support.ProtocolUtils;
import com.googlecode.actorom.support.FailoverPolicies;
import com.googlecode.actorom.support.TopologyException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import net.jcip.annotations.ThreadSafe;

/**
 * {@link com.googlecode.actorom.Topology} implementation based on sockets and asynchronous I/O,
 * enabling communication between different, remote, topologies and actors.<br>
 * Every RemoteTopology instance is bound to a specific host address and port, and is able to:
 * <ul>
 * <li>Locally spawn actors.</li>
 * <li>Access its own locally spawned actors, as well as other RemoteTopology actors by using their {@link RemoteAddress}.</li>
 * </ul>
 * So, actors belonging to different RemoteTopology instances are able to communicate and exchange messages.
 *
 * @author Sergio Bossa
 */
@ThreadSafe
public class RemoteTopology extends AbstractTopology<RemoteAddress> {

    private final String host;
    private final int port;
    private final MessageChannel messageChannel;
    private final Map<RemoteAddress, RemoteActorProxy> remoteActors;
    private final ExecutorService remoteFuturesExecutor;

    /**
     * Create a remote topology using the following defaults:
     * {@link com.googlecode.actorom.support.ThreadingPolicies#newGreenThreadingPolicy()} and
     * {@link com.googlecode.actorom.support.FailoverPolicies#newNoFailoverPolicy()}.
     *
     * @param host The host address this topology will listen to for remote connections.
     * @param port The port this topology will listen to for remote connections.
     */
    public RemoteTopology(String host, int port) {
        this(host, port, ThreadingPolicies.newGreenThreadingPolicy(), FailoverPolicies.newNoFailoverPolicy());
    }

    /**
     * Create a remote topology using the provided {@link com.googlecode.actorom.ThreadingPolicy},
     * and the {@link com.googlecode.actorom.support.FailoverPolicies#newNoFailoverPolicy()} default.
     *
     * @param host The host address this topology will listen to for remote connections.
     * @param port The port this topology will listen to for remote connections.
     * @param threadingPolicy
     */
    public RemoteTopology(String host, int port, ThreadingPolicy threadingPolicy) {
        this(host, port, threadingPolicy, FailoverPolicies.newOneForOnePolicy());
    }

    /**
     * Create a remote topology using the provided {@link com.googlecode.actorom.FailoverPolicy},
     * and the {@link com.googlecode.actorom.support.ThreadingPolicies#newGreenThreadingPolicy()} default.
     *
     * @param host The host address this topology will listen to for remote connections.
     * @param port The port this topology will listen to for remote connections.
     * @param failoverPolicy
     */
    public RemoteTopology(String host, int port, FailoverPolicy failoverPolicy) {
        this(host, port, ThreadingPolicies.newGreenThreadingPolicy(), failoverPolicy);
    }

    /**
     * Create a remote topology using the provided {@link com.googlecode.actorom.ThreadingPolicy} and
     * {@link com.googlecode.actorom.FailoverPolicy}.
     *
     * @param host The host address this topology will listen to for remote connections.
     * @param port The port this topology will listen to for remote connections.
     * @param threadingPolicy
     * @param failoverPolicy
     */
    public RemoteTopology(String host, int port, ThreadingPolicy threadingPolicy, FailoverPolicy failoverPolicy) {
        super(threadingPolicy, failoverPolicy);
        try {
            this.host = host;
            this.port = port;
            messageChannel = new MessageChannel(host, port, new CommandCallbackImpl());
            remoteActors = new HashMap<RemoteAddress, RemoteActorProxy>();
            // TODO : should be properly set-up/configured?
            remoteFuturesExecutor = Executors.newCachedThreadPool();
            //
            messageChannel.bind();
        } catch (IOException ex) {
            throw new TopologyException(ex.getMessage(), ex);
        }
    }

    public synchronized RemoteAddress spawnActor(String id, Object handler) {
        RemoteAddress address = new RemoteAddress(host, port, id);
        boolean spawned = doSpawnActor(address, handler);
        if (spawned) {
            return address;
        } else {
            return null;
        }
    }

    public synchronized Actor getActor(RemoteAddress address) {
        if (isLocal(address)) {
            return doGetActor(address);
        } else if (isRemote(address)) {
            RemoteActorProxy remote = doGetRemoteActorProxy(new Host(host, port), new Host(address.getHost(), address.getPort()), address);
            if (remote.isActive()) {
                remoteActors.put(address, remote);
                return remote;
            } else {
                remoteActors.remove(address);
                return null;
            }
        } else {
            return null;
        }
    }

    public synchronized void shutdown() {
        messageChannel.unbind();
        remoteFuturesExecutor.shutdownNow();
        remoteActors.clear();
        doShutdown();
    }

    private synchronized boolean isLocal(RemoteAddress address) {
        return (address.getHost().equals(host) && address.getPort() == port);
    }

    private synchronized boolean isRemote(RemoteAddress address) {
        return (!address.getHost().equals(host) || address.getPort() != port);
    }

    private synchronized RemoteActorProxy doGetRemoteActorProxy(Host sender, Host receiver, RemoteAddress address) {
        RemoteActorProxy remote = remoteActors.get(address);
        if (remote == null) {
            remote = new RemoteActorProxy(sender, receiver, address);
        }
        return remote;
    }

    private class CommandCallbackImpl implements CommandCallback {

        public boolean sendMessage(SendCommand command) {
            Actor recipientActor = doGetActor(command.getMessageRecipient());
            if (recipientActor != null) {
                recipientActor.send(command.getMessage());
                return true;
            } else {
                return false;
            }
        }

        public boolean sendMessageWithFuture(final SendWithFutureCommand command) {
            Actor recipientActor = doGetActor(command.getMessageRecipient());
            if (recipientActor != null) {
                final FutureResult future = recipientActor.send(command.getMessage(), command.getTimeoutInNanos(), TimeUnit.NANOSECONDS);
                remoteFuturesExecutor.execute(new Runnable() {

                    public void run() {
                        future.await();
                        if (future.isCompleted()) {
                            Host sender = command.getHeader().getSender();
                            String correlationId = command.getHeader().getCommandId();
                            MessageChannelConnector channelConnector = new MessageChannelConnector(sender.getHost(), sender.getPort());
                            try {
                                String responseId = ProtocolUtils.generateCommandId();
                                CommandHeader header = new CommandHeader(new Host(host, port), sender, responseId, correlationId);
                                channelConnector.connect();
                                channelConnector.sendAsync(new CompleteCommand(header, command.getMessageRecipient(), future.getResult(), future.getException()));
                            } catch (IOException ex) {
                            } finally {
                                channelConnector.disconnect();
                            }
                        }
                    }
                });
                return true;
            } else {
                return false;
            }
        }

        public boolean completeFuture(CompleteCommand command) {
            RemoteActorProxy remote = remoteActors.get(command.getMessageRecipient());
            if (remote != null) {
                remote.completeFuture(command.getHeader().getCorrelationId(), command.getResult(), command.getException());
            }
            return true;
        }

        public boolean linkActor(LinkCommand command) {
            RemoteAddress fromAddress = command.getFromAddress();
            Actor fromActor = doGetActor(fromAddress);
            if (fromActor != null) {
                RemoteAddress toAddress = command.getToAddress();
                Actor toActor = doGetActor(toAddress);
                if (toActor == null) {
                    toActor = doGetRemoteActorProxy(new Host(host, port), new Host(toAddress.getHost(), toAddress.getPort()), toAddress);
                }
                fromActor.link(toActor);
                return true;
            } else {
                return false;
            }
        }

        public boolean unlinkActor(UnlinkCommand command) {
            RemoteAddress fromAddress = command.getFromAddress();
            Actor fromActor = doGetActor(fromAddress);
            if (fromActor != null) {
                RemoteAddress toAddress = command.getToAddress();
                Actor toActor = doGetActor(toAddress);
                if (toActor == null) {
                    toActor = doGetRemoteActorProxy(new Host(host, port), new Host(toAddress.getHost(), toAddress.getPort()), toAddress);
                }
                fromActor.unlink(toActor);
                return true;
            } else {
                return false;
            }
        }

        public boolean isActiveActor(IsActiveCommand command) {
            Actor actor = doGetActor(command.getAddress());
            if (actor != null && actor.isActive()) {
                return true;
            } else {
                return false;
            }
        }
    }
}
